<template>
  <!-- 新建销售SKU -->
  <a-modal
    v-model="visibleAddSKU"
    okText="保存"
    cancelText="取消"
    :title="skuTit"
    @ok="handleOk"
    width="836px"
    @cancel="closeModel"
  >
    <p>
      系统SKU：
      <a-select
        show-search
        placeholder="系统SKU"
        option-filter-prop="children"
        style="width: 200px"
        :filter-option="filterOption"
        v-model="selectItem"
        @change="handleChange"
      >
        <a-select-option
          :value="item.key"
          :chineseName="item.chineseName"
          v-for="item in SKUCode"
          :key="item.key"
          :sku="item.sku"
        >
          {{ item.sku }}
        </a-select-option>
      </a-select>
      * <a-input :maxLength="128" placeholder="产品数量" v-model="tableDatas.fkList.skuAmount" />
      <a-button type="primary" style="margin-left: 20px" @click="addRowSkuSell">
        添加
      </a-button>
    </p>
    <a-table
      :columns="columns"
      :data-source="tableDatas.fkList"
      :pagination="false"
      :scroll="{ y: 400, x: 770 }"
      bordered
      size="small"
    >
      <span slot="skuAmount" class="action" slot-scope="text, record">
        <a-input :maxLength="128" v-model="record.skuAmount" style="width:100px" />
      </span>
      <span slot="action" slot-scope="text, record">
        <a-popconfirm
          title="确认删除该条数据吗?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="delRows(record)"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </span>
    </a-table>
    <a-form-model :model="tableDatas" ref="ruleForm" :rules="rules">
      <a-form-model-item prop="saleSkuCode" label="销售SKU:">
        <a-input
        :maxLength="128"
          placeholder="请输入唯一的销售SKU"
          v-model="tableDatas.saleSkuCode"
        />
      </a-form-model-item>
      <a-form-model-item class="textarea" label="备注:">
        <a-textarea :maxLength="256" v-model="tableDatas.remarks" :rows="1" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { SKUSell_page } from "@/apis/clientSide/SKUManage/SKUsell";
// import { nanoid } from "nanoid"; //nanoid为函数
import {
  SKUSell_select,
  SKUSell_add,
  SKU_update
} from "@/apis/clientSide/SKUManage/SKUsell";
export default {
  props: ["getTabSKUsellData"],
  mounted() {
    this.$bus.$off("visibleAddSKU");
    this.$bus.$on("visibleAddSKU", () => {
      this.visibleAddSKU = true;
      this.oldSkuSell = null;
      this.tableDatas.fkList = [];
      this.tableDatas.saleSkuCode = "";
      this.editFlag = false;
    });
    this.editRow();
  },
  created() {
    this.getSKUType();
  },
  data() {
    const checkSellSKU = async (rule, value, callback) => {
      this.SKUsellData.saleSkuCode = value;
      if (value === this.oldSkuSell) {
        callback();
      } else {
        if (value) {
          let { code, responseBody } = await SKUSell_page(this.SKUsellData);
          if (code == "200") {
            if (responseBody.records.length != 0) {
              callback(new Error("销售SKU已存在，请重新填写！"));
            } else {
              callback();
            }
          }
        } else {
          callback(new Error("请填写销售SKU！"));
        }
      }
    };
    return {
      skuTit: "新增销售SKU",
      selectItem: undefined,
      skus: "",
      editFlag: false,
      //新建SKU表格
      visibleAddSKU: false,
      // 系统SKU列表
      SKUCode: [],
      //添加入表格数据
      tableDatas: {
        chineseName: "",
        createBy: 0,
        createTime: "",
        current: 0,
        endTime: "",
        fkList: [],
        remarks: "",
        revision: 0,
        saleSkuCode: "",
        size: 0,
        skuAmount: 0,
        skuId: 0,
        startTime: "",
        tenantId: 0,
        updateBy: 0,
        updateTime: ""
      },
      SKUsellData: {
        chineseName: "",
        createBy: 0,
        createTime: "",
        current: 1,
        endTime: "",
        fkList: [
          {
            createBy: 0,
            createTime: "",
            remarks: "",
            revision: 0,
            saleSkuFkId: 0,
            saleSkuId: 0,
            skuAmount: 0,
            skuId: 0,
            tenantId: 0,
            updateBy: 0,
            updateTime: ""
          }
        ],
        remarks: "",
        revision: 0,
        saleSkuCode: "",
        saleSkuId: 0,
        size: 10,
        skuAmount: 0,
        skuId: 0,
        skus: "",
        startTime: "",
        tenantId: 0,
        updateBy: 0,
        updateTime: ""
      },
      rules: {
        saleSkuCode: [
          { validator: checkSellSKU, required: true, trigger: "blur" }
        ]
      },
      oldSkuSell: null
    };
  },
  methods: {
    //添加到表格
    addRowSkuSell() {
      let flag = false;
      if (this.tableDatas.fkList.length >= 1) {
        this.tableDatas.fkList.forEach(item => {
          if (this.skus === item.skus) {
            flag = true;
          }
        });
      }
      if (!flag) {
        if (
          this.tableDatas.skus != "" &&
          this.tableDatas.chineseName != "" &&
          this.tableDatas.fkList.skuAmount != ""
        ) {
          this.tableDatas.fkList.push({
            skus: this.tableDatas.skus,
            chineseName: this.tableDatas.chineseName,
            skuAmount: this.tableDatas.fkList.skuAmount,
            key: this.tableDatas.fkList.length,
            skuId: this.tableDatas.id
          });
        } else {
          this.$message.error("请完善系统SKU及数量信息！");
        }
      } else {
        this.$message.error("相同的sku只能添加一个！");
      }
    },
    //模态框确定
    handleOk() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return false;
        } else {
          if (!this.editFlag) {
            if (
              this.tableDatas.saleSkuCode != "" &&
              this.tableDatas.fkList.length >= 1
            ) {
              this.tableDatas.skus = "";
              this.tableDatas.fkList.forEach(item => {
                this.tableDatas.skus +=
                  this.tableDatas.skus === ""
                    ? `${item.skus}`
                    : "," + `${item.skus}`;
              });
              let { code } = await SKUSell_add(this.tableDatas);
              if (code === "10000") {
                this.getTabSKUsellData();
                this.visibleAddSKU = false;
              }
            } else {
              this.$message.error("请输入销售SKU并添加表格信息！");
            }
          } else if (this.editFlag) {
            if (
              this.tableDatas.saleSkuCode != "" &&
              this.tableDatas.fkList.length >= 1
            ) {
              this.tableDatas.skus = "";
              this.tableDatas.fkList.forEach(item => {
                this.tableDatas.skus +=
                  this.tableDatas.skus === ""
                    ? `${item.skus}`
                    : "," + `${item.skus}`;
              });
              let { code } = await SKU_update(this.tableDatas);
              if (code === "10000") {
                this.getTabSKUsellData();
                this.visibleAddSKU = false;
              }
            } else {
              this.$message.error("请输入销售SKU并添加表格信息！");
            }
          }
        }
      });
    },
    //系统SKU下拉框改变
    handleChange(value, option) {
      this.skus = option.data.attrs.sku;
      this.tableDatas.id = value;
      this.tableDatas.skus = option.data.attrs.sku;
      this.tableDatas.chineseName = option.data.attrs.chineseName;
    },
    //下拉框过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    async getSKUType() {
      let { code, responseBody } = await SKUSell_select();
      if (code === "200") {
        this.SKUCode = responseBody;
      }
    },
    editRow() {
      this.$bus.$off("SkuSellRowData");
      this.$bus.$on("SkuSellRowData", rowData => {
        this.oldSkuSell = rowData.saleSkuCode;
        this.skuTit = "编辑销售SKU";
        this.tableDatas = { ...rowData };
        this.visibleAddSKU = true;
        this.editFlag = true;
      });
    },
    //删除每一行
    delRows(record) {
      this.tableDatas.fkList.forEach((item, i) => {
        if (record.key === item.key) {
          this.tableDatas.fkList.splice(i, 1);
          this.$message.success("删除成功");
        }
      });
    },
    closeModel() {
      this.tableDatas = {
        chineseName: "",
        createBy: 0,
        createTime: "",
        current: 0,
        endTime: "",
        fkList: [],
        remarks: "",
        revision: 0,
        saleSkuCode: "",
        size: 0,
        skuAmount: 0,
        skuId: 0,
        startTime: "",
        tenantId: 0,
        updateBy: 0,
        updateTime: ""
      };
      this.selectItem = undefined;
      this.$refs.ruleForm.resetFields();
    }
  },
  computed: {
    columns() {
      return [
        {
          title: "系统SKU",
          dataIndex: "skus",
          align: "center",
          // scopedSlots: { customRender: "selfClassifyName" },
          ellipsis: true,
          width: "20%"
        },
        {
          title: "产品名称",
          dataIndex: "chineseName",
          align: "center",
          width: "20%",
          ellipsis: true,
          scopedSlots: { customRender: "chineseName" }
        },
        {
          title: "数量",
          dataIndex: "skuAmount",
          scopedSlots: { customRender: "skuAmount" },
          align: "center",
          width: "20%",
          ellipsis: true
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 120
        }
      ];
    }
  }
};
</script>

<style lang="less" scoped>
input {
  width: auto;
}
/deep/.ant-form {
  margin-top: 15px;
  .ant-form-item {
    display: flex;
    width: 100%;
    .ant-form-item-label {
      width: 80px;
      text-align: right;
    }
  }
  .textarea {
    .ant-form-item-control-wrapper {
      width: 100%;
      .ant-input {
        width: 80%;
      }
    }
  }
}
</style>
